import openpyxl
import os
import xlwt


def transform_xls_to_txt(target_file_path, result_file_path):

	if not target_file_path.endswith(".xlsx") and not target_file_path.endswith(".xls"):
		raise Exception("无效格式的文件") 

	if os.path.exists(result_file_path) == False:
		os.mknod(result_file_path)

	wb = openpyxl.load_workbook(target_file_path)
	text = ""
	sheetnames = wb.sheetnames
	for sheetname in sheetnames:
		sheet = wb[sheetname]
		rownum = sheet.max_row
		colnum = sheet.max_column 
		for i in range(1, rownum+1):
			for j in range(1, colnum+1):
				text += sheet.cell(i,j).value + " "
			text += "\n"

	with open(result_file_path,'w') as file:
		file.write(text)
		file.close()

def write_list_to_new_xls(workbook_name, sheets):
	# {"sheet1":[["java","python","c++"],["spring","numpy","openssl"]]}
	
	if not workbook_name.endswith(".xls"):
		raise Exception("无效格式的文件，更改输出文件格式为.xls") 

	wb = xlwt.Workbook(encoding='utf-8')
	for sheetname, sheetvalue in sheets.items():
		sheet = wb.add_sheet(sheetname)
		for i in range(len(sheetvalue)):
			for j in range(len(sheetvalue[i])):

				sheet.write(i, j, sheetvalue[i][j])

	wb.save(workbook_name)

if __name__ == "__main__":
	#transform_xls_to_txt("..//material//test.xlsx", "..//output//xls_output.txt")
	sheets = {"sheet1":[["java","python","c++"],["spring","numpy","openssl"]],
			"sheet2":[["apple","orange","binary"],["police","cup","iphone"]]
	}
	write_list_to_new_xls("..//material//testwrite.xls", sheets)